<?php

namespace App\Http\Controllers;

use App\Jobs\SendSms;
use App\Models\AcceptRecord;
use App\Models\Group;
use App\Http\Requests\AcceptRequest;
use App\Models\Customer;
use App\Models\Project;
use App\Models\User;
use App\Models\WxClient;
use App\Plugins\Sms\SendInfo;
use App\Services\AdminService;
use App\Services\HelpService;
use Illuminate\Http\Request;
use Auth;

class ApiController extends Controller
{
    /**
     * 获取微信二维码图片
     * @param Request $request
     * @return array
     */
    function qrcode(Request $request)
    {
        // 权限处理
        // 传递过来的wxClientId 必须在当前登录用户负责的项目关联的wx_id中
        $wxClientId = $request->wxClientId;
        if (empty($wxClientId)) {
            return $this->_error('没有传递微信id参数');
        }

        // 获取图片
        $path = config('filesystems.qrcode.img')
            . '/' . $wxClientId . '.png';
        if (file_exists($path)) {
            $img_content = file_get_contents($path);
            header("content-type: image/png");
            echo $img_content;
            exit;
        } else {
            return $this->_error('该微信号没有二维码图片');
        }
    }

    /**
     * 认领客户
     * @param AcceptRequest $request
     * @return array|string
     */
    function accept(AcceptRequest $request){
        // 仅操作员可访问 TODO: 这一版只考虑账号最底层使用(社长和管家), 不考虑上级账号
        // 获取操作员负责的项目
        $user = Auth::User();
        // 当前用户负责的项目
        $project_ids = Project::whereIn('users', [$user->id])
            ->orWhereIn('mangers', [$user->id])
            ->get()
            ->pluck('id')
            ->all();
        if (empty($project_ids)) {
            return $this->_error('此用户没有负责的项目');
        }
        $project_id = $project_ids[0];
        $data['customer_id'] = $request->input('customer_id');
        $data['company_id'] = $user->company_id;
        $data['user_id'] = $user->id;
        $data['project_id'] = $project_id;
        // 查询项目下是否存在传入客户
        $customer = Customer::find($data['customer_id']);
        if (!is_null($customer)) {
            $project_ids = $customer->projects;
            if (!in_array($project_id, $project_ids)) {
                return $this->_error('没有权限认领此客户');
            }
        } else {
            return $this->_error('此客户不存在');
        }
        // 如果存在符合认领条件的项目
        // 调用更新认领表逻辑
        $admin_service = new AdminService();
        $is_save = $admin_service->updateAcceptRecord($data);
        if ($is_save){
            return "modify success";
        } else {
            return $this->_error('此客户已被认领');
        }
    }

    /**
     * 误认领客户
     * @param Request $request
     * @return array
     */
    public function mistakenAccept(Request $request) {
        $user = request()->user();
        $data = $request->all();
        $acceptor = $data['acceptor'];  //误认领了该客户的用户手机号码
        $customer_id = $data['customer_id'];    //客户ID
        $acceptUser = User::where('mobile', $acceptor)->first();
        if (empty($acceptUser)) {
            return $this->_error('此客户不存在');
        }
        $acceptRecord = AcceptRecord::where(['user_id' => $acceptUser->id, 'customers' => $customer_id])->first();
        if (!is_null($acceptRecord)) {
            // 获取认领记录中project_id指向的Project->users中的isManager == true的User
            $project = Project::find($acceptRecord->project_id);
            $mobiles = [];
            // 先找project中users中有没有isManager
            foreach ($project->users as $userId) {
                $user = User::find($userId);
                // 找到isManger，发短信
                if ($user->isManager == true) {
                    $mobile = $user->mobile;
                    array_push($mobiles, $mobile);
                }
            }
            // 没有找到isManger，开始递归查找上级负责人
            if (empty($mobiles)) {
                $parentGroup = $project->group->getParent();
                if (count($parentGroup->users) > 0) {
                    $users = $parentGroup->users;
                    $mobiles = $users->pluck('mobile')->all();
                } else {
                    $parent_id = $parentGroup->parent_id;
                    $users = $this->getParentUsers($parent_id);
                    $mobiles = $users->pluck('mobile')->all();
                }
            }
            //取出加好友的信息
            $wx = WxClient::find($project->wx_id)->first();
            $contact = [];
            if ($wx && $wx->contacts) {
                foreach ($wx->contacts as $value) {
                    if ($value['customer_id'] == $customer_id) {
                        array_push($contact, $value);
                    }
                }
                $contact = array_collapse($contact);
            } else {
                return $this->_error('此客户不存在');
            }
            // 获取误认领短信模板，发短信给上述获取的手机号
            $_filter = [
                'customer' => $contact['nickName'] ? $contact['nickName'] : $contact['account'],   //客户昵称
                'addTime' => date('Y-m-d H:i:s', $contact['addTime']),    //加好友时间
                'colleague' => $acceptUser->name,  //同事
                'colleagueNum' => $acceptUser->mobile, //同事手机号码
                'sendTo' => $user->name, //当前申述人的姓名
                'sendToNum' => $user->mobile   //当前申述人的手机
            ];
            $data = ['_code' => 2, '_filter' => $_filter, '_mobiles' => $mobiles];
            $job = (new SendSms($data));
            $this->dispatch($job);
        } else {
            return $this->_error('此客户不存在');
        }

    }

    /**
     * 递归查询users
     * @param $parent_id
     * @return mixed
     */
    public function getParentUsers(&$parent_id){
        $parentGroup = Group::find($parent_id);
        if (count($parentGroup->users) > 0) {
            return $parentGroup->users;
        } else {
            $this->getParentUsers($parentGroup->parent_id);
        }
    }

}

